<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ComfyUI Image Processing</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .upload-form {
            margin-bottom: 20px;
        }
        .preview {
            max-width: 100%;
            margin: 20px 0;
        }
        .preview img {
            max-width: 100%;
            border-radius: 4px;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .status.pending {
            background-color: #fff3cd;
        }
        .status.completed {
            background-color: #d4edda;
        }
        .status.failed {
            background-color: #f8d7da;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:disabled {
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>ComfyUI Image Processing</h1>
        
        <div class="upload-form">
            <div class="form-group">
                <label for="workflowSelect">Select Workflow:</label>
                <select id="workflowSelect"></select>
            </div>
            <div class="form-group">
                <label for="imageInput">Choose Image:</label>
                <input type="file" id="imageInput" accept="image/*">
            </div>
            <button onclick="uploadImage()" id="uploadButton">Upload and Process</button>
        </div>

        <div class="preview">
            <h3>Input Image:</h3>
            <img id="inputPreview" style="display: none;">
        </div>

        <div id="status" class="status" style="display: none;"></div>

        <div class="preview">
            <h3>Result:</h3>
            <img id="resultPreview" style="display: none;">
        </div>
    </div>

    <script>
        let currentTaskId = null;
        let statusCheckInterval = null;

        // 加载工作流列表
        async function loadWorkflows() {
            try {
                const response = await fetch('/workflows');
                const workflows = await response.json();
                const select = document.getElementById('workflowSelect');
                workflows.forEach(workflow => {
                    const option = document.createElement('option');
                    option.value = workflow.id;
                    option.textContent = workflow.name;
                    select.appendChild(option);
                });
            } catch (error) {
                console.error('Error loading workflows:', error);
            }
        }

        // 页面加载时获取工作流列表
        loadWorkflows();

        document.getElementById('imageInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.getElementById('inputPreview');
                    img.src = e.target.result;
                    img.style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        });

        async function uploadImage() {
            const fileInput = document.getElementById('imageInput');
            const workflowSelect = document.getElementById('workflowSelect');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('Please select an image first');
                return;
            }

            const formData = new FormData();
            formData.append('image', file);
            formData.append('workflow_id', workflowSelect.value);

            document.getElementById('uploadButton').disabled = true;
            document.getElementById('status').innerHTML = 'Uploading...';
            document.getElementById('status').className = 'status pending';
            document.getElementById('status').style.display = 'block';
            document.getElementById('resultPreview').style.display = 'none';

            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                if (response.ok) {
                    currentTaskId = data.task_id;
                    startStatusCheck();
                } else {
                    throw new Error(data.error || 'Upload failed');
                }
            } catch (error) {
                document.getElementById('status').innerHTML = `Error: ${error.message}`;
                document.getElementById('status').className = 'status failed';
                document.getElementById('uploadButton').disabled = false;
            }
        }

        async function startStatusCheck() {
            if (statusCheckInterval) {
                clearInterval(statusCheckInterval);
            }

            statusCheckInterval = setInterval(async () => {
                try {
                    const response = await fetch(`/status/${currentTaskId}`);
                    const data = await response.json();

                    document.getElementById('status').innerHTML = `Status: ${data.status}`;
                    
                    if (data.status === 'completed') {
                        clearInterval(statusCheckInterval);
                        document.getElementById('status').className = 'status completed';
                        document.getElementById('uploadButton').disabled = false;
                        
                        // 显示结果图片
                        if (data.result) {
                            const resultImg = document.getElementById('resultPreview');
                            // 获取第一个输出图片的路径
                            const imageKeys = Object.keys(data.result);
                            if (imageKeys.length > 0) {
                                const firstImage = data.result[imageKeys[0]];
                                if (firstImage && firstImage.images && firstImage.images.length > 0) {
                                    resultImg.src = `/outputs/${firstImage.images[0].filename}`;
                                    resultImg.style.display = 'block';
                                }
                            }
                        }
                    } else if (data.status === 'failed') {
                        clearInterval(statusCheckInterval);
                        document.getElementById('status').className = 'status failed';
                        document.getElementById('status').innerHTML = `Error: ${data.error}`;
                        document.getElementById('uploadButton').disabled = false;
                    }
                } catch (error) {
                    console.error('Status check failed:', error);
                }
            }, 1000);
        }
    </script>
</body>
</html>
